﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Serialization;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
using MVVM.Core;

namespace ObjectModel.Excel
{
    /// <summary>
    /// Holds serializable information about a range object's parent workbook and worksheet.
    /// </summary>
    public class OfflineRange : NotificationBase, IOfflineRange
    {
        private readonly Application mApp = Globals.Application;
        private string mAddress = string.Empty;
        private string mAddressWithSheetName = string.Empty;
        private string mWorksheetName;

        public OfflineRange() // Parameterless constructor required for serialization.
        {
        	Workbook = mApp.ActiveWorkbook;
        }
        
        public OfflineRange(Range range) : this()
        {
            Range = range;
        }

        [XmlIgnore]
        public virtual Range Range
        {
            get
            {                
                return GetRangeFromAddress();
            }

            set
            {
                //Workbook = value.Worksheet.Parent;
                Worksheet = value.Worksheet;
                Address = value.Address;
                AddressWithSheetName = value.GetAddressWithSheetName();
                
            }
        }

        protected virtual Range GetRangeFromAddress()
        {
        	try { return mApp.Range[AddressWithSheetName]; }
            catch (COMException) { throw new InvalidOperationException("Could not resolve range from literal reference."); }
        }

        public string Address // To be serialized. Must be public.
        {
            get { return mAddress; }
            set
            {
                mAddress = value;
                OnPropertyChanged("Address");
            }
        }

        public string AddressWithSheetName
        {
            get { return mAddressWithSheetName; }
            set 
            {
                mAddressWithSheetName = value;
                OnPropertyChanged("AddressWithSheetName");
            }
        }

        public string WorksheetName  // To be serialized. Must be public.
        {
            get { return mWorksheetName; }
            set
            {
                mWorksheetName = value;
                OnPropertyChanged("WorksheetName");
            }
        }

    	[XmlIgnore]
    	public virtual Workbook Workbook { get; set; }

        [XmlIgnore]
        public Worksheet Worksheet
        {
            get { return Workbook.GetWorksheetFromName(WorksheetName); }
            set { WorksheetName = value.Name; }
        }

        public void Select()
        {
            ((_Worksheet)Worksheet).Activate();
            Range.Select();
        }
    }
}
